<template>
  <div class="container">
    <!--头部筛选 start-->
    <div class="flex-row justify-between p_b10">
      <div>
        <el-input size="small" v-model="params.filter" placeholder="搜索关键词..." class="m_r10 width200"></el-input>
        <el-button size="small" type="primary" icon="el-icon-search" @click="onPageChange(1)"></el-button>
        <el-button size="small" type="primary" @click="onPageChange(1)">刷新</el-button>
      </div>
      <div>
      </div>
    </div>
    <!--头部筛选 end-->

    <!--列表数据 start-->
    <el-table :data="tableData" border size="mini">
      <el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>
      <el-table-column prop="name" :min-width="100" label="用户名"></el-table-column>
      <el-table-column prop="phone" :min-width="120" label="手机号码" align="center"></el-table-column>
      <el-table-column prop="email" :min-width="120" label="邮箱"></el-table-column>
      <el-table-column prop="sex" :min-width="120" label="性别" align="center">
        <template v-slot="{row}">
          <el-tag type="info">{{ row.sex === 'male' ? '男' : '女' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="balance" :min-width="120" align="center" label="余额（元）"></el-table-column>
      <!--<el-table-column prop="idNumber" :min-width="120" label="身份证号"></el-table-column>-->

      <el-table-column label="操作" :width="120" align="center" fixed="right">
        <template #default="{row}">
          <el-button type="text" icon="el-icon-coin" @click="toggleChargeModal(true,row)" size="mini">充值</el-button>
          <!--<el-button type="text" icon="el-icon-edit" @click="toggleEditorModal(true,row)" size="mini">编辑</el-button>-->
          <!--<el-button type="text" icon="el-icon-delete" @click="onDestroy(row)" size="mini">删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <!--列表数据 end-->


    <!--分页组件 start-->
    <div class="pagination">
      <el-pagination
          background layout="total, prev, pager, next"
          :current-page="pageMeta.current_page"
          :page-size="pageMeta.limit" :total="pageMeta.total"
          @current-change="onPageChange"></el-pagination>
    </div>
    <!--分页组件 end-->

    <!--充值 start-->
    <el-dialog
        v-model="chargeFormData.show"
        title="余额充值"
        width="50%">
      <el-form :model="chargeFormData" label-width="120px">
        <el-form-item label="充值用户">
          {{ chargeFormData.user.name }} （{{ chargeFormData.user.phone }}）
        </el-form-item>
        <el-form-item label="用户邮箱">
          {{ chargeFormData.user.email }}
        </el-form-item>
        <el-form-item label="充值金额(元)">
          <el-input-number v-model="chargeFormData.price" placeholder="充值金额"></el-input-number>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="chargeFormData.remarks" placeholder="备注"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="toggleChargeModal(false)">取消</el-button>
          <el-button size="small" type="primary" @click="onCharge()">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!--分类编辑、新增弹框 start-->
    <el-dialog
        v-model="formData.show"
        :title="formData.data.id>0?'编辑':'新增'"
        width="50%">
      <el-form
          ref="formRefName"
          :rules="rules"
          :model="formData.data" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.data.name" placeholder="请填写名称"></el-input>
        </el-form-item>
        <el-form-item label="价格(元)" prop="price">
          <el-input-number v-model="formData.data.price" placeholder="请填写价格"></el-input-number>
        </el-form-item>
        <el-form-item label="必选服务包">
          <el-radio-group v-model="formData.data.isBind">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="结算时退款">
          <el-radio-group v-model="formData.data.needRefund">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="toggleEditorModal(false)">取消</el-button>
          <el-button size="small" type="primary" @click="onSubmit()">提交</el-button>
        </div>
      </template>
    </el-dialog>
    <!--分类编辑、新增弹框 end-->
  </div>


</template>

<script>
import {defineComponent, reactive, ref, toRaw} from "vue"
import {usePageMeta} from "../../hooks/usePageTableData";
import {deepClone} from "../../utils/helpers";
import Toast from "../../utils/Toast";
import Member from "../../api/modules/Member";

export default defineComponent({
  name: "Member",
  data() {
    return {
      rules: {
        name: [
          {required: true, message: "请填写名称"}
        ],
        price: [
          {required: true, message: "请填写价格"},
          {type: 'number', min: 0, max: 99999, transform: v => Number(v) || '', message: "价格范围在0~99999之间"},
        ]
      },
    }
  },
  setup() {
    const formRefName = ref(null);
    const pageHandle = usePageMeta();
    const params = reactive({
      filter: "",
    });
    const tableData = ref([]);


    onPageChange(1); // 初始化时直接请求一次分类列表

    const formData = reactive({
      show: false,
      data: {
        id: 0,
        isBind: 0, // 是否是默认必选服务包，1是，0不是
        needRefund: 0, // 是否需要在订单结算时退款，1是，0不是
        name: '',
        price: '',
      }
    });

    const chargeFormData = reactive({
      show: false,
      type: 1, // 1：充值
      price: '',
      remarks: '',
      user: {
        id: 0,
        name: "",
        phone: "",
        email: "",
      }
    });

    const _chargeFormData = deepClone(toRaw(chargeFormData));

    // 充值
    function toggleChargeModal(show, user = {}) {
      if (!show) {
        chargeFormData.type = 1;
        chargeFormData.price = '';
        chargeFormData.remarks = '';

      }
      chargeFormData.show = show;
      chargeFormData.user = Object.assign({}, _chargeFormData.user, user);
    }

    function toggleEditorModal(show, data = {}) {
      formData.show = show;
      formData.data = Object.assign({}, _formData.data, data);
      if (formRefName.value) {
        formRefName.value.resetFields();
      }

    }

    function onSubmit() {
      if (!formRefName.value) {
        Toast.error('找不到表单')
        return;
      }
      formRefName.value.validate(async (valid) => {
        if (!valid) {
          return;
        }
        const _formData = deepClone(toRaw(formData)).data;
        try {
          let res = {}
          delete _formData.createTime;
          delete _formData.updateTime;
          if (_formData.id > 0) {
            res = await Member.update(_formData)
            onPageChange()
          } else { // 新增操作
            delete _formData.id;
            res = await Member.create(_formData);
            onPageChange(1)
          }
          Toast.success(res.message || '操作成功');
          toggleEditorModal(false)
        } catch (e) {
          Toast.error(e.message);
        }

      })
    }

    async function onDestroy(row) {
      const canDestroy = await Toast.confirm();
      if (!canDestroy) {
        return;
      }
      try {
        const res = await Member.destroy(row.id);
        Toast.success(res.message || '删除成功');
        if (tableData.value.length === 1) {
          onPageChange(1);
        } else {
          onPageChange();

        }
      } catch (e) {
        console.log(e)
        Toast.error(e.message || '删除失败')
      }
    }

    async function onPageChange(page) {
      const pageMeta = deepClone(toRaw(pageHandle.pageMeta.value));
      if (page) {
        pageMeta.index = page;
      }
      try {
        const {data} = await Member.lists({
          ...pageMeta,
          ...params,
        });
        tableData.value = data.data || [];
        pageHandle.updatePageMeta(pageMeta.index, data.count);

      } catch (e) {
        console.log(e);
      }
    }

    async function onCharge() {
      if (!chargeFormData.user.id) {
        Toast.error("找不到充值用户")
        return
      }
      const price = Math.abs(Number(chargeFormData.price) || 0)
      if (price === 0) {
        Toast.error("充值金额必须大于0")
        return
      }
      try {
        await Member.charge({
          price,
          userId: chargeFormData.user.id,
          remarks: chargeFormData.remarks,
        });
        Toast.success('充值成功');
        toggleChargeModal(false)
        onPageChange();
      } catch (e) {
        Toast.error(e.message);
      }
    }

    return {
      ...pageHandle,
      params,
      onCharge,
      toggleChargeModal,
      chargeFormData,
      onSubmit,
      formData,
      formRefName,
      toggleEditorModal,
      onDestroy,
      tableData,
      onPageChange,
    }
  },
})
</script>

<style lang="scss" scoped>

</style>
